package net.alteiar.plateform.game;

import java.util.concurrent.TimeUnit;

/**
 * A wrapper class that provides timing methods. This class provides us with a
 * central location where we can add our current timing implementation.
 * Initially, we're going to rely on the GAGE timer. (@see
 * http://java.dnsalias.com)
 * 
 * @author Kevin Glass
 */
public class SystemTimer {
	/**
	 * Get the high resolution time in nanoseconds
	 * 
	 * @return The high resolution time in nanoseconds
	 */
	public static long getTime() {
		// return time in nano
		return System.nanoTime();
	}

	/**
	 * 
	 * @param duration
	 *            The amount of time in milliseconds to sleep for
	 */
	public static void sleep(long duration) {
		sleep(0, duration);
	}

	public static TimeUnit getTimeUnit() {
		return TimeUnit.NANOSECONDS;
	}

	/**
	 * Sleep for a fixed number of milliseconds.
	 * 
	 * @param beginTime
	 *            The time that elapse before you ask to sleep
	 * @param duration
	 *            The amount of time in nanoseconds to sleep for
	 */
	public static void sleep(long beginTime, long duration) {

		duration -= TimeUnit.NANOSECONDS.convert(2, TimeUnit.MILLISECONDS);

		// finally pause for a bit.
		while ((getTime() - beginTime) < duration) {

			long timeToSleep = getTime() - beginTime;
			timeToSleep = TimeUnit.MILLISECONDS.convert(timeToSleep,
					SystemTimer.getTimeUnit());

			timeToSleep -= 5;

			if (timeToSleep < 0) {
				timeToSleep = 1;
			}
			try {
				// we sleep a little less so we are sure to wake up at right
				// time
				Thread.sleep(timeToSleep);
			} catch (Exception e) {
			}
		}
	}
}
